package com.maddox.relax.bluetooth

import android.bluetooth.BluetoothSocket
import android.os.Bundle
import android.os.Handler
import com.maddox.relax.util.LogUtil
import java.lang.RuntimeException
import kotlin.concurrent.thread

/**
 * @author Maddox
 * 蓝牙客户端服务管理,传输数据
 */
class MyBluetoothService(private val handler: Handler) {

    private lateinit var connectedThread: ConnectedThread
    private lateinit var mmSocket: BluetoothSocket


    companion object {
        val MESSAGE_READ: Int = 0 //读取
        val MESSAGE_WRITE: Int = 1//写入
        val MESSAGE_TOAST: Int = 2//提示
    }

    /**
     * 初始化蓝牙连接
     */
    fun init(socket: BluetoothSocket?) {
        if (socket == null) return
        mmSocket = socket
        connectedThread = ConnectedThread(mmSocket)
        connectedThread.start()
    }

    /**
     * 向蓝牙服务设备发送数据
     */
    fun sendData(bytes: ByteArray) {
        if (mmSocket == null) throw RuntimeException("请先调用init方法初始化连接")
        try {
            Thread {
                write(bytes)
            }.start()
        } catch (e: Exception) {
            LogUtil.d("开启写入线程失败:$e")
        }

    }


    //向蓝牙服务器写入数据
    fun write(byteArray: ByteArray) {
        try {
            LogUtil.d("开始写入数据")
            mmSocket.outputStream.write(byteArray)
        } catch (e: Exception) {
            LogUtil.d("写入蓝牙服务器失败")
            //将失败信息发送到消息池
            val writeErrorMsg = handler.obtainMessage(MESSAGE_TOAST)
            val bundle = Bundle().apply {
                putString("toast", "向蓝牙服务器发送数据失败")
            }
            writeErrorMsg.data = bundle
            handler.sendMessage(writeErrorMsg)
            return
        }
        //发送数据成功进行通知
        val writeMsg = handler.obtainMessage(MESSAGE_WRITE, -1, -1, ByteArray(1024))
        writeMsg.sendToTarget()
    }



    fun cancel() {
        try {
            mmSocket.close()
        } catch (e: Exception) {
            LogUtil.d("关闭蓝牙服务连接失败")
        }
    }



    private inner class ConnectedThread(socket: BluetoothSocket) : Thread() {
        private val mmInputStream = socket.inputStream;
        private val mmBuffer = ByteArray(1024)

        override fun run() {
            //读取到的字节数
            var numBytes: Int
            //监听服务端的数据
            while (true) {
                numBytes = try {
                    mmInputStream.read(mmBuffer)
                } catch (e: Exception) {
                    LogUtil.d("读取蓝牙服务数据失败")
                    break
                }
                //将读取到的数据发到消息池  读取  读取到字节数  -1 字节数组
                val readMsg = handler.obtainMessage(MESSAGE_READ, numBytes, -1, mmBuffer)
                readMsg.sendToTarget()
            }

        }



    }


}